/**
 * Copyright (C) T-Systems International, 2013-2014
 *
 * The copyright of the computer program herein is the property of
 * T-Systems International. The program may be used and/or copied
 * only with the written permission of T-Systems International or in
 * accordance with the terms and conditions stipulated in the
 * agreement/contract under which the program has been supplied.
 *
 * $Author$
 * $Date$
 * $Rev$
 */
package com.tsystems.migdb.sftp.server;

import com.jcraft.jsch.KeyPair;
import lombok.AllArgsConstructor;
import lombok.NonNull;

import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.RSAPublicKeySpec;

@AllArgsConstructor
public class OpenSshUtils {

    @NonNull
    private final String algorithmName;
    @NonNull
    private final String algorithm;

    public PublicKey decodePublicKey(byte[] bytes) throws Exception {
        KeyPair pair = KeyPair.load(null, null, bytes);
        ByteBuffer bb = ByteBuffer.wrap(pair.getPublicKeyBlob());
        int len = bb.getInt();
        byte[] type = new byte[len];
        bb.get(type);
        if (algorithmName.equals(new String(type))) {
            BigInteger e = decodeBigInt(bb);
            BigInteger m = decodeBigInt(bb);
            RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e);
            return KeyFactory.getInstance(algorithm).generatePublic(spec);
        } else {
            throw new IllegalArgumentException("Only supports " + algorithm);
        }
    }

    public BigInteger decodeBigInt(ByteBuffer bb) {
        int len = bb.getInt();
        byte[] bytes = new byte[len];
        bb.get(bytes);
        return new BigInteger(bytes);
    }

}